﻿using Max.PH5_2011A.DTO;
using Max.PH5_2011A.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.PH5_2011A.API.Controllers.Car
{
    /// <summary>
    /// 购物车控制器
    /// </summary>
    [Route("car")]
    [ApiController]
    public class ShoppingCarController : ControllerBase
    {

        /*
         * 1 要连接到redis服务器
         * **/
        //1、安装CsRedisCore
        //2、实例化一个客户端就可以啦
        //3、127.0.0.1是你的redis服务器所在的地址
        //4、6379是指你的redis服务器的端口
        CSRedis.CSRedisClient _redis = new CSRedis.CSRedisClient("127.0.0.1:6379");


        IProductSkuService _skuService;

        public ShoppingCarController(IProductSkuService skuService)
        {
            _skuService = skuService;
        }


        #region List

        /// <summary>
        /// 将商品添加到购物车
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(ShoppingCarProductDto dto)
        {
            //redis存放数据，是用什么形式？---Key/Value
            string key = dto.MemberId;  //key以用户（会员）唯一标识符来作为存放在redis中唯一标识

            List<ShoppingCarProductDto> list = _redis.Get<List<ShoppingCarProductDto>>(key);

            if (list != null)
            {

                var m = list.Where(x => x.ProductSkuId.Equals(dto.ProductSkuId)).FirstOrDefault();
                if (m == null)
                {
                    list.Add(dto);
                }
                else
                {
                    m.ProductNumber += dto.ProductNumber;
                }
            }
            else
            {
                list = new List<ShoppingCarProductDto>();
                list.Add(dto);
            }
            //redis操作：取和放值(读和写)，用的get/set
            _redis.Set(key, list);

            return Ok();
        }

        /// <summary>
        /// 获取购物车中的数据（根据会员Id)
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Query(string key)
        {
            var list = _redis.Get<List<ShoppingCarProductDto>>(key);

            return Ok(list);
        }

        /// <summary>
        /// 删除购物车数据
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult Delete(List<ShoppingCarProductDto> dtos)
        {
            if (dtos != null || string.IsNullOrEmpty(dtos[0].MemberId))
            {
                //返回参数不合法的提示信息
            }

            //删除数据，删哪里的数据？-----删除的购物车Redis中的数据
            //所以要把Redis中的数据拿出来
            //new CSRedis.CSRedisClient("127.0.0.1:6379");

            //key？？？？是什么，在哪里
            var key = dtos[0].MemberId; //在集合中,memberid都是一样的，所以随便取第一条数据中的memberid即可
            var data = _redis.Get<List<ShoppingCarProductDto>>(key);

            dtos.ForEach(x =>
            {
                var m = data.Where(p => p.ProductSkuId.Equals(x.ProductSkuId)).FirstOrDefault();

                if (m != null)
                {
                    data.Remove(m);
                }
            });
            //更新Redis缓存数据
            _redis.Set(key, data);

            return Ok();
        }


        /// <summary>
        /// 修改购物车
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Update(ShoppingCarProductDto dto)
        {

            if (string.IsNullOrEmpty(dto.MemberId))
            {
                //参数不合法
            }

            var key = dto.MemberId;

            var data = _redis.Get<List<ShoppingCarProductDto>>(key);

            var m = data.Where(x => x.ProductSkuId.Equals(dto.ProductSkuId)).FirstOrDefault();
            if (m != null)
            {
                m.ProductNumber = dto.ProductNumber;
            }

            _redis.Set(key, data);

            return Ok();
        }

        #endregion

        #region Hash

        /// <summary>
        /// 哈唏添加数据到购物车
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("hash")]
        public IActionResult HAdd(ShoppingCarProductDto dto)
        {

            ResponseResultDto<dynamic> result = new();

            //单次购买的数量，， dto.ProductNumber
            //库存
            var model = _skuService.Query().Where(x => dto.ProductSkuId.Equals(x.Id.ToString())).FirstOrDefault();
            if( dto.ProductNumber > model.IvildStock)
            {
                result.Code = ResponseStateCode.STOCKNOENOUGHT;
                result.Message = "库存不足";
                return Ok(result);
            }

            if (string.IsNullOrEmpty(dto.MemberId) || string.IsNullOrEmpty(dto.ProductSkuId))
            {
                result.Code = ResponseStateCode.PARAMNOVALID;
                result.Message = "无效参数";
                return Ok(result);
            }

            string key = dto.MemberId;

            //根据用户ID和产品ID获取一条数据
            var data = _redis.HGet<ShoppingCarProductDto>(key, dto.ProductSkuId);

            if (data != null)
            {
                //如果已存在，则数量累加
                data.ProductNumber += dto.ProductNumber;

                if (data.ProductNumber > model.IvildStock)
                {
                    result.Code = ResponseStateCode.STOCKNOENOUGHT;
                    result.Message = "库存不足";
                    return Ok(result);
                }

                //重新更新到redis中
                _redis.HSet(key,dto.ProductSkuId,data);
            }
            else
            {
                _redis.HSet(key, dto.ProductSkuId, dto);
            }

            return Ok(result);
        }


        /// <summary>
        /// 哈希修改购物车数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut("hash")]
        public IActionResult HUpdate(ShoppingCarProductDto dto)
        {
            ResponseResultDto<dynamic> result = new();
            if (string.IsNullOrEmpty(dto.MemberId) || string.IsNullOrEmpty(dto.ProductSkuId))
            {
                result.Code = ResponseStateCode.PARAMNOVALID;
                result.Message = "无效参数";
                return Ok(result);
            }

            var model = _skuService.Query().Where(x => dto.ProductSkuId.Equals(x.Id.ToString())).FirstOrDefault();
            if (dto.ProductNumber > model.IvildStock)
            {
                result.Code = ResponseStateCode.STOCKNOENOUGHT;
                result.Message = "库存不足";
                return Ok(result);
            }

            string key = dto.MemberId;
            string field = dto.ProductSkuId;
            //从redis中获取需要修改的那条数据
            var data = _redis.HGet<ShoppingCarProductDto>(key, field);
            if (data != null)
            {
                data.ProductNumber = dto.ProductNumber;
                _redis.HSet(key, field, data);
            }
            else
            {
                result.Code = ResponseStateCode.PARAMNOVALID;
                result.Message = "无效参数";
                return Ok(result);
            }

            return Ok(result);
        }

        /// <summary>
        /// 哈唏删除购物车数据
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        [HttpDelete("hash")]
        public IActionResult HDelete(List<ShoppingCarProductDto> dtos)
        {
            ResponseResultDto<dynamic> result = new();
            if (dtos == null || string.IsNullOrEmpty(dtos[0].MemberId) || string.IsNullOrEmpty(dtos[0].ProductSkuId))
            {
                result.Code = ResponseStateCode.PARAMNOVALID;
                result.Message = "无效参数";
                return Ok(result);
            }

            string key = dtos[0].MemberId;
            //从redis中对应的key里，删除对应的商品id集合
            long d = _redis.HDel(key, dtos.Select(x => x.ProductSkuId).ToArray());
            if (d <= 0)
            {
                result.Code = ResponseStateCode.PARAMNOVALID;
                result.Message = "无效操作";
            }

            return Ok(result);
        }

        /// <summary>
        /// 哈唏查询购物车数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet("hash")]
        public IActionResult HQuery(string key)
        {
            ResponseResultDto<dynamic> result = new();
            if (string.IsNullOrEmpty(key))
            {
                result.Code = ResponseStateCode.PARAMNOVALID;
                result.Message = "无效参数";
                return Ok(result);
            }

            //获取redis中key的所有hash值（默认是dictionary）
            var data = _redis.HGetAll<ShoppingCarProductDto>(key);

            //将dictionary中的值放到集合中
            List<ShoppingCarProductDto> list = new();
            foreach (var item in data)
            {
                list.Add(item.Value);
            }

            result.Data = list;

            return Ok(result);
        }

        #endregion


        #region 20230531

        [HttpPost("20230531")]
        public IActionResult Add20230531(ShoppingCarProductDto dto)
        {
            //需要将dto放到购物车（redis）中

            //连接到redis服务器
            //CsRedisCore -----安装包
            var redis = new CSRedis.CSRedisClient("127.0.0.1:6379");

            string key = dto.MemberId;
            string field = dto.ProductSkuId;

            //用hash的方式，直接拿redis中这个会员的这个商品数据
            var m = redis.HGet<ShoppingCarProductDto>(key, field);
            if (m != null)
            {
                m.ProductNumber += dto.ProductNumber;
                redis.HSet(key,field, m);
            }
            else { 
                redis.HSet(key, field, dto);
            }
            return Ok("添加成功");
        }

        #endregion
    }
}
